package com.gmall.utils;

import com.alibaba.fastjson.JSONObject;
import com.gmall.common.GmallConfig;
import redis.clients.jedis.Jedis;

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.List;

public class DimUtil {
    public static JSONObject getDimInfo(Connection connection,String tableName,String id) throws Exception {
        //查询Phoenix之前先查询Redis
        Jedis jedis = RedisUtil.getJedis();

        //查询DIM
        String redisKey = "DIM" + tableName + ":" + id;
        String diminfoJSONStr = jedis.get(redisKey);

        if (diminfoJSONStr!=null){
            //重置过期时间
            jedis.expire(redisKey,24*60*60);
            //归还连接
            jedis.close();
            //返回结果
            return JSONObject.parseObject(diminfoJSONStr);
        }

        //拼接查询语句
        String querySql = "select * from "+ GmallConfig.HBASE_SCHEMA+"."+tableName+"where id ='"+id+"'";

        //查询Phoenix
        List<JSONObject> queryList = JdbcUtil.queryList(connection, querySql, JSONObject.class, false);
        JSONObject dimInfoJson = queryList.get(0);

        //在返回结果之前，将数据写入Redis
        jedis.set(redisKey,dimInfoJson.toJSONString());
        jedis.expire(redisKey,24*60*60);
        jedis.close();
        return dimInfoJson;

    }
    public static void delRedisDimInfo(String tableName, String id) {
        Jedis jedis = RedisUtil.getJedis();
        String rediskey = "DIM:" + tableName + ":" + id;
        jedis.del(rediskey);
        jedis.close();
    }

    public static void main(String[] args) throws Exception {
        Class.forName(GmallConfig.PHOENIX_DRIVER);
        Connection connection = DriverManager.getConnection(GmallConfig.PHOENIX_SERVER);

        System.out.println(getDimInfo(connection,"DIM_BASE_TRADEMARK","15"));

        connection.close();
    }

}
